import { useState, useEffect, forwardRef, useImperativeHandle } from "react";
import { Card, Input, Tree } from "antd";
import styles from "./index.less";
import { SearchOutlined } from "@ant-design/icons";
const tabListNoTitle = [
  {
    key: 'org',
    tab: '组织机构',
  },
];
const dataList: { key: any; title: any; label: string }[] = [];
const generateList = (data: any) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const { key } = node;
    dataList.push({ key, title: data[i].title, label: data[i].title });
    if (node.children) {
      generateList(node.children);
    }
  }
};

const getParentKey = (key: any, tree: any[]): any => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item: any) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

interface Props {
  initData: any[],
  data: any[],
  multiple: boolean,
  onSelect: (data: any) => void,
  deleteKeys: number[]
}

const OrgTreeCom = forwardRef((props: Props, ref) => {

  const [tabActive, setTabActive] = useState('org');
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([150, 1693]);
  const [checkedKeys, setCheckedKeys] = useState<any[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  useImperativeHandle(ref, () => ({
    onOk: () => {
      if (props.multiple) {
        return checkedKeys;
      } else {
        return selectedKeys;
      }
    }
  }))

  const deleteChecked = (key: number[]) => {
    if (props.multiple && key.length) {
      setCheckedKeys(checkedKeys.filter(item => {
        return item !== key[0]
      }))
    } else if (!props.multiple && key.length) {
      setSelectedKeys(selectedKeys.filter(item => {
        return item !== key[0]
      }))
    }
  }
  useEffect(() => {
    if (props.initData.length) {
      const itemKeys = props.initData.map(item => {
        return item.key
      })
      if (props.multiple) {
        setCheckedKeys(itemKeys);
      } else {
        setSelectedKeys(itemKeys)
      }
    }
  }, [props.initData])
  useEffect(() => {
    if (props.deleteKeys.length) {
      deleteChecked(props.deleteKeys)
    }
  }, [props.deleteKeys])
  const onCheck = (checkedKeysValue: any, info: any) => {
    if (props.multiple) {
      props.onSelect && props.onSelect(info.checkedNodes)
    }
    setCheckedKeys(checkedKeysValue);
  };
  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    if (!props.multiple) {
      props.onSelect && props.onSelect(info.selectedNodes)
    }
    setSelectedKeys(selectedKeysValue);
  };
  const loop = (data: any[]): any =>
    data.map(item => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className={styles.treeSearchValue}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return { title, key: item.key, label: item.title, children: loop(item.children) };
      }
      return {
        title,
        key: item.key,
      };
    });
  const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const expandedKeys = dataList
      .map(item => {
        if (item.title.includes(value)) {
          return getParentKey(item.key, props.data);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(expandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  }
  useEffect(() => {
    generateList(props.data);
  }, [])

  return (
    <Card
      style={{ width: '100%', height: 480 }}
      tabList={tabListNoTitle}
      activeTabKey={tabActive}
      tabBarExtraContent={
        <Input prefix={<SearchOutlined />} placeholder="搜索" onChange={(e) => onSearch(e)} />
      }
      onTabChange={key => {
        setTabActive(key)
      }}
    >
      <Tree
        height={380}
        checkable={props.multiple}
        selectable={!props.multiple}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        treeData={loop(props.data)}
      />
    </Card>

  )
})
export default OrgTreeCom;
